package com.example.waterdispenserm2.mo.ttl.d;


import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.aill.androidserialport.SerialPort;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

/**
 * 串口管理类 - 负责TTL串口的打开、关闭、数据收发
 */
public class SerialPortManager {



    private SerialPort serialPort;
    private static final String TAG = "SerialPortManager";
    private InputStream mInputStream;
    private OutputStream mOutputStream;
    private OnDataReceivedListener mListener;
    private ReadThread mReadThread;

    private boolean isOpen = false;


    /**
     * 打开串口
     */
    public boolean openSerialPort(String devicePath) {
        try {
            serialPort = new SerialPort(new File(devicePath), 9600, 0);
            mInputStream = serialPort.getInputStream();
            mOutputStream = serialPort.getOutputStream();
            isOpen = true;

            // 启动读取线程
            startReadThread();
            return true;
        } catch (Exception e) {
            Log.e(TAG, "串口操作异常: " + e.getMessage());
            return false;
        }
    }

    /**
     * 关闭串口
     */
    public void closeSerialPort() {
        stopReadThread();
        try {
            if (mInputStream != null) mInputStream.close();
            if (mOutputStream != null) mOutputStream.close();
        } catch (IOException e) {
            Log.e(TAG, "关闭流异常: " + e.getMessage());
        }
    }

    /**
     * 发送数据 (带引导码)
     */
    public void sendDataWithGuide(byte[] data) {
        if (mOutputStream == null || data == null) return;

        try {
            // 发送引导码 (2ms低电平)
            mOutputStream.write(0x00);
            mOutputStream.flush();
            Thread.sleep(TTLInductionCookerProtocolUtil.GUIDE_CODE_DURATION_MS);

            // 发送数据帧
            mOutputStream.write(data);
            mOutputStream.flush();
            Log.i(TAG, "发送数据: " + TTLInductionCookerProtocolUtil.bytesToHex(data));
        } catch (Exception e) {
            Log.e(TAG, "发送数据失败: " + e.getMessage());
        }
    }

    /**
     * 启动读取线程
     */
    private void startReadThread() {
        stopReadThread();
        mReadThread = new ReadThread();
        mReadThread.start();
    }

    /**
     * 停止读取线程
     */
    private void stopReadThread() {
        if (mReadThread != null) {
            mReadThread.interrupt();
            mReadThread = null;
        }
    }

    /**
     * 数据读取线程
     */
    private class ReadThread extends Thread {
        @Override
        public void run() {
            super.run();
            byte[] buffer = new byte[1024];
            while (!isInterrupted()) {
                try {
                    if (mInputStream == null) return;
                    int size = mInputStream.read(buffer);
                    if (size > 0 && mListener != null) {
                        byte[] data = new byte[size];
                        System.arraycopy(buffer, 0, data, 0, size);
                        mListener.onDataReceived(data);
                    }
                } catch (IOException e) {
                    Log.e(TAG, "读取数据失败: " + e.getMessage());
                    break;
                }
            }
        }
    }

    /**
     * 数据接收回调接口
     */
    public interface OnDataReceivedListener {
        void onDataReceived(byte[] data);
    }

    /**
     * 设置数据接收监听器
     */
    public void setOnDataReceivedListener(OnDataReceivedListener listener) {
        this.mListener = listener;
    }


}



